package com.dexilaonian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dexilaonian.R;
import com.dexilaonian.bean.ConfirmBean;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Logutil;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.view.LoadingDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import okhttp3.Call;

public class HomeDetailActivity extends AppCompatActivity implements View.OnClickListener {
    private String home;
    private ImageView share;
    private ImageView myLove;
    private int isPosition;
    private String isUrl;
    private TextView home_title;
    private LoadingDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_detail);
        Intent intent = getIntent();
        home_title = (TextView) findViewById(R.id.base_title_homeDetail);
        dialog = new LoadingDialog(this);

        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                home = extras.getString("HOME");
                String home_tag = extras.getString("HOME_TAG");
                if (home_tag.equals("1")) {
                    home_title.setText("最新");
                } else if (home_tag.equals("2")) {
                    home_title.setText("慢性病");
                }else if (home_tag.equals("3")) {
                    home_title.setText("康养");
                }else if (home_tag.equals("4")) {
                    home_title.setText("饮食");
                }
                else if (home_tag.equals("5")) {
                    home_title.setText("急救");
                }
                Logutil.e("TTTHOMEDetail====="+home+"==homeTitle"+home_tag);
            }
        }
        share = (ImageView) findViewById(R.id.iv_share);
        myLove = (ImageView) findViewById(R.id.iv_love);
        share.setOnClickListener(this);
        myLove.setOnClickListener(this);
        ImageView back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             finish();
            }
        });
        WebView webView = (WebView) findViewById(R.id.home_detail);
        WebSettings webSettings = webView.getSettings();
        // 让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);
        // 让JavaScript可以自动打开windows
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 设置缓存
        webSettings.setAppCacheEnabled(true);
        // 设置缓存模式,一共有四种模式
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 设置缓存路径
//        webSettings.setAppCachePath("");
        // 支持缩放(适配到当前屏幕)
        webSettings.setSupportZoom(true);
        // 将图片调整到合适的大小
        webSettings.setUseWideViewPort(true);
        // 支持内容重新布局,一共有四种方式
        // 默认的是NARROW_COLUMNS
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 设置可以被显示的屏幕控制
        webSettings.setDisplayZoomControls(true);
        // 设置默认字体大小
        webSettings.setDefaultFontSize(12);
        String url = Constant.base_url + "/news/detail/"+ home;
        // 设置WebView的客户端
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;// 返回false
            }
        });
        webView.loadUrl(url);
        initLove();
    }


    private void initLove() {
         String love_url = Constant.base_url +"/news/isLike.do";
         Map<String, String> map = new HashMap<>();
        map.put("newsId",home);
        Okhttp.postString(true, love_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {

            }
            @Override
            public void onResponse(String response, int id) {
                Log.e("TTTTISLIKE", response);
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
               /*     if (status == 34 || status == 16) {
                        startActivity(new Intent(HomeDetailActivity.this, LoginActivity.class));
                        return;
                    }*/
                    if (status == 37||status==0) {
                        myLove.setImageDrawable(getDrawable(R.drawable.dianjizan));//已经点赞
                        isPosition = 1;
                    } else {
                        myLove.setImageDrawable(getDrawable(R.drawable.weidianjizan));//没点赞
                        isPosition = 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_love:   //isPosition = 0时是未点赞, ==1时是已经点赞
                if (isPosition == 0) {
                    isUrl = Constant.base_url + "/news/like.do";
                    initGetLove(home);
                } else if (isPosition == 1) {
                    isUrl = Constant.base_url + "/news/dislike.do";
                    initGetLove(home);
                }
                break;
            case R.id.iv_share:
                showShare();
                break;
        }
    }

    private void initGetLove(final String s) {
        Map<String, String> map = new HashMap<>();
        map.put("newsId", s);
        Okhttp.postString(true, isUrl, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("TTTTISLIKE222", response);
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(HomeDetailActivity.this, LoginActivity.class));
                        return;
                    }
                    Logutil.e("TTTP="+isPosition);
                    if (isPosition == 0 && (status == 37||status ==0)) {
                        myLove.setImageDrawable(getDrawable(R.drawable.dianjizan));
                        isPosition =1;
                        Toast.makeText(HomeDetailActivity.this,"点赞成功",Toast.LENGTH_SHORT).show();
                    } else {
                        myLove.setImageDrawable(getDrawable(R.drawable.weidianjizan));
                        isPosition =0;
                        Toast.makeText(HomeDetailActivity.this,"取消点赞成功",Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {

            }
        });
    }

    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        /*oks.addHiddenPlatform(QQ.NAME);
        oks.setImageData();*/
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, cn.sharesdk.framework.Platform.ShareParams paramsToShare) {
                if ("SinaWeibo".equals(platform.getName())) {
                    paramsToShare.setText("我是文本,分享链接通过拼接文本方式分享链接" + "http://sharesdk.cn");
                            paramsToShare.setImageUrl("https://hmls.hfbank.com.cn/hfapp-api/9.png ");
                    /*paramsToShare.setFilePath(ResourcesManager.getInstace(MobSDK.getContext()).getFilePath());*/
                   /* paramsToShare.setUrl("http://sharesdk.cn");*/
                }
                if ("Wechat".equals(platform.getName())) {
                    paramsToShare.setTitle("标题");
                    paramsToShare.setUrl("http://sharesdk.cn");
                            paramsToShare.setText("我是共用的参数，这几个平台都有text参数要求，提取出来啦");
                    /*paramsToShare.setW*/
                    /*Bitmap imageData = BitmapFactory.decodeResource(getResources(), R.drawable.ssdk_logo);
                    paramsToShare.setImageData(imageData);*/
                    paramsToShare.setImageUrl("https://hmls.hfbank.com.cn/hfapp-api/9.png ");
                            paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                }

                if ("WechatMoments".equals(platform.getName())) {
                    paramsToShare.setTitle("标题");
                    paramsToShare.setUrl("http://sharesdk.cn ");
                            paramsToShare.setText("我是共用的参数，这几个平台都有text参数要求，提取出来啦");
                    paramsToShare.setImageUrl("https://hmls.hfbank.com.cn/hfapp-api/9.png ");
                            paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                }
                if ("QQ".equals(platform.getName())) {
                    paramsToShare.setTitle("标题");
                    paramsToShare.setTitleUrl("http://sharesdk.cn");
                            paramsToShare.setText("我是共用的参数，这几个平台都有text参数要求，提取出来啦");
                    paramsToShare.setImageUrl("https://hmls.hfbank.com.cn/hfapp-api/9.png");
                }
                if ("Facebook".equals(platform.getName())) {
                    //Facebook空间您自己写了
                    paramsToShare.setText("我是共用的参数，这几个平台都有text参数要求，提取出来啦");
                    paramsToShare.setImageUrl("https://hmls.hfbank.com.cn/hfapp-api/9.png");
                }
                if ("QZone".equals(platform.getName())) {
                    //QQ空间您自己写了
                    paramsToShare.setTitle("标题");
                    paramsToShare.setTitleUrl("http://sharesdk.cn");
                    paramsToShare.setText("我是共用的参数，这几个平台都有text参数要求，提取出来啦");
                    paramsToShare.setImageUrl("https://hmls.hfbank.com.cn/hfapp-api/9.png");
                }
                if("Alipay".equals(platform.getName())){
                    paramsToShare.setTitle("标题");
                    paramsToShare.setUrl("http://sharesdk.cn");
                            paramsToShare.setText("我是共用的参数，这几个平台都有text参数要求，提取出来啦");
                    /*Bitmap imageData = BitmapFactory.decodeResource(getResources(), R.drawable.ssdk_logo);
                    paramsToShare.setImageData(imageData);*/
                    paramsToShare.setImageUrl("https://hmls.hfbank.com.cn/hfapp-api/9.png");
                            paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                }
            }
        });
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.e("ShareLogin", "onComplete ---->  分享成功");
                share.setImageDrawable(getResources().getDrawable(R.drawable.fenxiang));
                Toast.makeText(HomeDetailActivity.this,"分享成功",Toast.LENGTH_SHORT).show();
                platform.getName();
            }
            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.e("ShareLogin", "onError ---->  失败" + throwable.getStackTrace()+"==" + throwable.getMessage());
                Toast.makeText(HomeDetailActivity.this,"分享失败",Toast.LENGTH_SHORT).show();
                throwable.printStackTrace();
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.e("ShareLogin", "onCancel ---->  分享取消");
                Toast.makeText(HomeDetailActivity.this,"分享取消",Toast.LENGTH_SHORT).show();
            }
        });
// 启动分享GUI
        oks.show(this);
    }
}
